<?php
class AuthController extends Zend_Controller_Action
{
	
	public function init()
	{
		$auth = Zend_Auth::getInstance();
		$userInfo = $auth->getStorage()->read();
		$groupBase = new GroupBase();
		if ($userInfo) {
			$userGroups = $groupBase->getUserGroup($userInfo->name);
		}
		$this->_userGroup = $userGroups[0]['name'] ? $userGroups[0]['name'] : "Users";
		$this->_acl = new Acl_PPMIS();
		$this->view->acl = $this->_acl;
		$this->view->userGroup = $this->_userGroup;
	}
	
	public function preDispatch()
	{
		
		$auth = Zend_Auth::getInstance();
		/* if (!$auth->getIdentity()) {
			$this->_redirect('auth/login');
		}*/
		if($auth->getIdentity()) {
			$userInfo = $auth->getStorage()->read();
			$this->view->userInfo = $userInfo;
		}
		$Configuration = new Configuration();
		$configurationData = $Configuration->getConfigurationInfo();
		$this->view->configuration = $configurationData;
		$this->view->current = 'home';
	}
	
	public function loginAction()
	{
		$userBase = new UserBase();
		$propertyEntry = new PropertyEntry();
		$propertyString = new PropertyString();
		
		$form = new LoginForm();
		
		if ($this->getRequest()->isPost()) {
			$formData = $this->_request->getPost();
			if ($form->isValid($formData)) {
				//Zend_Debug::dump($formData);
				$users = new Users();
				$auth = Zend_Auth::getInstance();
				$auth->setStorage(new Zend_Auth_Storage_Session('Zend_Auth'));
				$authAdapter = new Zend_Auth_Adapter_DbTable($users->getAdapter());
				$authAdapter->setTableName('userbase');
				$authAdapter->setIdentityColumn('name');
				$authAdapter->setCredentialColumn('password');
				$authAdapter->setCredentialTreatment("MD5(?)");
				$authAdapter->setIdentity($formData['username']);
	            $authAdapter->setCredential($formData['password']);
				
				try {
					$result = $auth->authenticate($authAdapter);
					if ($result->isValid()) {
						$identity=$result->getIdentity();
						$resultantRow = $authAdapter->getResultRowObject(array(
							'id',
							'name',
							//'fullname',
							//'email'
						));
						
						$usersData = $userBase->getUserById($resultantRow->id);
						foreach ($usersData as $data) {
							if($data['property_key'] == 'fullname') {
								$resultantRow->fullname = $data['propertyvalue'];
							}
							if($data['property_key'] == 'Email') {
								$resultantRow->email = $data['propertyvalue'];
							}
						}
						
						$storage = $auth->getStorage();
						$storage->write($resultantRow);
						//$storage->write($userData);
						Zend_Debug::dump($storage->read());
						$this->_redirect('home');
						//Zend_Debug::dump($storage->read());
					} else {
						echo "Username or password is unvalid. Please try again.";
					}
				} catch (Zend_Exception $e) {
					echo $e->getMessage();
				}
			}
		}
		
		$this->view->form = $form;
	}
	public function signupAction()
	{
		$userBase = new UserBase();
		$propertyString = new PropertyString();
		$propertyEntry = new PropertyEntry();
		$membershipBase = new MembershipBase();
		
		$auth = Zend_Auth::getInstance();
		if ($auth->getIdentity()) {
			$this->_redirect('auth/login');
		}
		$form = new RegisterForm();
		$users = new Users();
		
		if ($this->getRequest()->isPost()) {
			$formData = $this->_request->getPost();
			if ($form->isValid($formData)) {
				if($formData['password'] != $formData['confirmPassword']) {
					$this->view->errorMsg['passwords_mismatch'] = "Password and confirm password must match.";
					$this->render('signup');
				}
				unset($formData['confirmPassword']);
				unset($formData['register']);
				unset($formData['cancel']);
				unset($formData['captaText']);
				try {
				$userBaseData = array(
					'name' => $formData['username'],
					'password' => md5($formData['password'])
				);
				
				$userBase->insert($userBaseData);
				$userId = $userBase->getAdapter()->lastInsertId();
				// inserting data in property string and property entry..
				
				$propertyEntryData = array(
					'entry_name' => 'OSUser',
					'entry_id' => $userId,
					'property_key' => 'Email',
					'propertytype' => 5
				);
				$propertyEntry->insert($propertyEntryData);
				$lastInsertId = $propertyEntry->getAdapter()->lastInsertId();
				
				$propertyStringData = array(
					'id' => $lastInsertId,
					'propertyvalue' => $formData['email']
				);
				
				$propertyString->insert($propertyStringData);
				
				$propertyEntryData = array(
					'entry_name' => 'OSUser',
					'entry_id' => $userId,
					'property_key' => 'fullname',
					'propertytype' => 5
				);
				$propertyEntry->insert($propertyEntryData);
				$lastInsertId = $propertyEntry->getAdapter()->lastInsertId();
				
				$propertyStringData = array(
					'id' => $lastInsertId,
					'propertyvalue' => $formData['fullName']
				);
				
				$propertyString->insert($propertyStringData);
				
				$membershipBaseData = array(
					'user_name' => $formData['username'],
					'group_name' => 'ppmis-users'
				);
				
				$membershipBase->insert($membershipBaseData);
				//Zend_Debug::dump($formData);
				$this->_redirect('home');
				
				} catch (Exception $e) {
					// exception code here.......
				}
			}
		}
		
		$this->view->form = $form;
	}
	public function logoutAction()
	{
		$this->_helper->viewRenderer->setNoRender();
		$this->_helper->layout->disableLayout();
		Zend_Auth::getInstance()->clearIdentity();
		$this->_redirect('auth/login');
	}
}